package com.reverie.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reverie.entity.Org;
import com.reverie.entity.User;
import com.reverie.mapper.OrgMapper;
import com.reverie.service.IOrgService;
import com.reverie.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements IOrgService {

    @Resource
    private IUserService userService;

    @Override
    public List<Tree<String>> getOrgTree() {
        Object loginId = StpUtil.getLoginId();
        User user = userService.getById(loginId.toString());
        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Org::getId, user.getOrgId())
                .or().in(Org::getParentId, user.getOrgId());
        List<Org> orgList = this.list(queryWrapper);

        List<Tree<String>> treeList = TreeUtil.build(orgList, "0", (treeNode, tree) -> {
            tree.setId(treeNode.getId());
            tree.setName(treeNode.getName());
            tree.setParentId(treeNode.getParentId());
            tree.setWeight(treeNode.getSortId());
            tree.putExtra("selectable",treeNode.getSelectable());
        });

        return treeList;
    }

    @Override
    public List<Org> listByParentId(Integer parentId) {
        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Org::getParentId, parentId);
        return list(queryWrapper);
    }
}
